<template>
  <header class="site-header">
    <div class="header-container">
      <!-- Logo -->
      <router-link to="/" class="logo">
        <img src="@/assets/logo.png" alt="学习平台" class="logo-image" />
        <span class="logo-text">
          <span class="text-learn">学无止境</span>
       
        </span>
      </router-link>
      
      <!-- Navigation -->
      <nav class="nav-menu">
        <router-link to="/" class="nav-item" :class="{ active: isActive('/') }">首页</router-link>
        <router-link to="/courses" class="nav-item" :class="{ active: isActive('/courses') }">课程</router-link>
      </nav>
      
      <!-- User Section -->
      <div class="user-section">
        <!-- Search Icon -->
        <el-tooltip content="搜索课程" placement="bottom">
          <el-button 
            class="search-btn" 
            circle 
            :icon="Search" 
            @click="showSearchDialog = true"
          />
        </el-tooltip>
        
        <!-- User not logged in -->
        <template v-if="!userStore.isLoggedIn">
          <router-link to="/login" class="login-btn">
            <el-button>登录</el-button>
          </router-link>
          <router-link to="/register" class="register-btn">
            <el-button type="primary" class="gradient-btn">注册</el-button>
          </router-link>
        </template>
        
        <!-- User logged in -->
        <template v-else>
          <!-- History Icon -->
          <el-tooltip content="浏览历史" placement="bottom">
            <el-button 
              class="history-btn" 
              circle 
              @click="openHistoryDrawer"
            >
              <el-icon><Clock /></el-icon>
            </el-button>
          </el-tooltip>
          
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-dropdown-link">
              <el-avatar 
                :size="36" 
                :src="formatAvatarUrl(userStore.userInfo.avatar)" 
                :icon="User"
              >
                {{ userStore.userInfo?.name?.charAt(0)?.toUpperCase() || userStore.userInfo?.username?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.name || userStore.userInfo?.username }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <template v-if="userStore.isUser">
                  <!-- Regular user links -->
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="favorites">
                    <el-icon><Star /></el-icon>
                    我的收藏
                  </el-dropdown-item>
                  <el-dropdown-item command="history">
                    <el-icon><Clock /></el-icon>
                    浏览历史
                  </el-dropdown-item>
                </template>
    
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </div>
    </div>
    
    <!-- Search Dialog -->
    <el-dialog v-model="showSearchDialog" title="搜索课程" width="500px" class="search-dialog">
      <el-input 
        v-model="searchQuery" 
        placeholder="输入课程名称、主题或技能..." 
        @keyup.enter="handleSearch"
        clearable
        :prefix-icon="Search"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
      
      <div v-if="recentSearches.length > 0" class="recent-searches">
        <div class="recent-header">
          <span>最近搜索</span>
          <el-button text type="primary" @click="clearRecentSearches">清除</el-button>
        </div>
        <div class="search-tags">
          <el-tag 
            v-for="(search, index) in recentSearches" 
            :key="index" 
            @click="selectRecentSearch(search)"
            class="search-tag"
            effect="light"
          >
            {{ search }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
    
    <!-- Browse History Drawer -->
    <BrowseHistoryDrawer :visible="showHistoryDrawer" @update:visible="showHistoryDrawer = $event" />
  </header>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search, ArrowDown, User, Star, SwitchButton, Clock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { ElMessageBox } from 'element-plus'
import BrowseHistoryDrawer from './BrowseHistoryDrawer.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const API_BASE_URL = process.env.VUE_APP_BASE_API || '/api'

// Data
const searchQuery = ref('')
const showSearchDialog = ref(false)
const showHistoryDrawer = ref(false)
const recentSearches = ref([])

// 格式化头像URL，确保包含API前缀
const formatAvatarUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整URL(包含http或https)，则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果已经包含API前缀，则直接返回
  if (url.startsWith(API_BASE_URL)) {
    return url
  }
  
  // 否则添加API前缀
  return `${API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
}

// Computed
const isActive = (path) => {
  return route.path === path || route.path.startsWith(`${path}/`)
}

// Methods
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'favorites':
      router.push('/favorites')
      break
    case 'history':
      openHistoryDrawer()
      break
    case 'logout':
      confirmLogout()
      break
  }
}

const openHistoryDrawer = () => {
  showHistoryDrawer.value = true
}

const confirmLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
    router.push('/')
  }).catch(() => {})
}

const handleSearch = () => {
  if (searchQuery.value.trim()) {
    addToRecentSearches(searchQuery.value.trim())
    router.push({
      path: '/courses',
      query: { search: searchQuery.value.trim() }
    })
    showSearchDialog.value = false
  }
}

const selectRecentSearch = (search) => {
  searchQuery.value = search
  handleSearch()
}

// Recent searches storage
const addToRecentSearches = (search) => {
  // Remove if already exists
  const index = recentSearches.value.indexOf(search)
  if (index > -1) {
    recentSearches.value.splice(index, 1)
  }
  
  // Add to beginning of array
  recentSearches.value.unshift(search)
  
  // Limit to 5 recent searches
  if (recentSearches.value.length > 5) {
    recentSearches.value = recentSearches.value.slice(0, 5)
  }
  
  // Save to localStorage
  localStorage.setItem('recentSearches', JSON.stringify(recentSearches.value))
}

const clearRecentSearches = () => {
  recentSearches.value = []
  localStorage.removeItem('recentSearches')
}

// Load recent searches from localStorage
onMounted(() => {
  const savedSearches = localStorage.getItem('recentSearches')
  if (savedSearches) {
    try {
      recentSearches.value = JSON.parse(savedSearches)
    } catch (e) {
      console.error('Failed to parse recent searches', e)
    }
  }
})
</script>

<style lang="scss" scoped>
.site-header {
  height: 70px;
  background-color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  height: 100%;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  text-decoration: none;
  margin-right: 40px;
  
  .logo-image {
    height: 30px;
    width: auto;
    margin-right: 10px;
  }
  
  .logo-text {
    display: flex;
    flex-direction: column;

    .text-learn {
      color: #4776E6;
      font-size: 25px;
      font-weight: 800;
      line-height: 1;
      letter-spacing: 1px;
    }

  }
}

.nav-menu {
  display: flex;
  flex: 1;
  
  .nav-item {
    padding: 0 20px;
    height: 70px;
    line-height: 70px;
    color: #555;
    text-decoration: none;
    font-size: 15px;
    font-weight: 500;
    transition: all 0.3s;
    position: relative;
    
    &:hover {
      color: #4776E6;
    }
    
    &.active {
      color: #4776E6;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 20%;
        right: 20%;
        height: 3px;
        background: var(--primary-gradient);
        border-radius: 3px 3px 0 0;
      }
    }
  }
}

.user-section {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .search-btn,
  .history-btn {
    font-size: 18px;
    box-shadow: 0 2px 8px rgba(71, 118, 230, 0.2);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(71, 118, 230, 0.3);
    }
  }
  
  .login-btn, .register-btn {
    text-decoration: none;
  }
  
  .gradient-btn {
    background: var(--primary-gradient);
    border: none;
    font-weight: 500;
    
    &:hover {
      background: linear-gradient(135deg, #3E68D3 0%, #7B49D2 100%);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(71, 118, 230, 0.3);
    }
  }
  
  .user-dropdown-link {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 6px 12px;
    border-radius: 30px;
    transition: all 0.3s;
    border: 1px solid rgba(71, 118, 230, 0.1);
    
    &:hover {
      background-color: rgba(71, 118, 230, 0.05);
      box-shadow: 0 2px 8px rgba(71, 118, 230, 0.1);
    }
    
    .el-avatar {
      border: 2px solid transparent;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      &:hover {
        border-color: #4776E6;
        transform: scale(1.05);
      }
    }
    
    .username {
      margin: 0 8px;
      font-size: 14px;
      font-weight: 500;
      color: #444;
    }
  }
}

.search-dialog {
  :deep(.el-dialog__header) {
    background: var(--primary-gradient);
    
    .el-dialog__title {
      color: white !important;
      -webkit-text-fill-color: white !important;
    }
  }
  
  :deep(.el-dialog__body) {
    padding-top: 24px;
  }
}

.recent-searches {
  margin-top: 24px;
  
  .recent-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    span {
      font-size: 14px;
      color: #666;
      font-weight: 500;
    }
  }
  
  .search-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    
    .search-tag {
      cursor: pointer;
      border-radius: 15px;
      padding: 6px 12px;
      transition: all 0.3s;
      border: 1px solid rgba(71, 118, 230, 0.3);
      
      &:hover {
        background-color: rgba(71, 118, 230, 0.1);
        transform: translateY(-2px);
        box-shadow: 0 2px 6px rgba(71, 118, 230, 0.2);
      }
    }
  }
}
</style> 